/*This is the GUI javascript for ee-ut-battleship created by Marko Tiidla and Priit Tiidla*/

/*
 * CANNOT USE THESE IN innerhtml :S
 * 
function drawMyBoard() {
	var ids = ['A','B','C','D','E','F','G','H','I','J'];
	document.write("<table>");
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
            document.write("<td title='0' data-overlap='0' id='"+i+ids[j]+"'class='droppable'></td>");
        }
        document.write("</tr>");
    } 
    document.write("</table>");
}
function drawOpponentBoard() {
	//var ids = ['AA','BB','CC','DD','EE','FF','GG','HH','II','JJ'];
	var ids = ['A','B','C','D','E','F','G','H','I','J'];
	document.write("<table>");
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
            document.write("<td id='"+i+ids[j]+"'class='enemy' onclick=''></td>");
        }
        document.write("</tr>");
    } 
    document.write("</table>");
}
*/



/*
 * Go from lobby to boards
 */
var mute = false;

this.client = null;

this.opponentName = "Vastane";
function drawGameBoards() {
	for (i in GAMES){
		if (GAMES[i].playerOne==client){
			opponentName = GAMES[i].playerTwo;
			break;
		}
		if (GAMES[i].playerTwo==client){
			opponentName = GAMES[i].playerOne;
			break;
		}
	}
	
	var change = document.getElementById("main");
	
	var text ='<div id="player">Sina</div> <div id="opponent">'+opponentName+'</div> <div id="sound" class="soundUnMuted" onClick="changeSound()"></div>' ; 

	var ids = ['A','B','C','D','E','F','G','H','I','J'];

	text += '<div id="myBoard" class="board">';
	text += "<table>";
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
        	  text += "<td title='0' data-overlap='0' id='"+i+ids[j]+"'class='droppable'></td>";
        }
         text += "</tr>";
    } 
    text += "</table> </div>";
    
    
    var ids = ['A','B','C','D','E','F','G','H','I','J'];
    text += '<div id="opponentBoard" class="board">';
    text += "<table>";
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
        	 text += "<td id='"+i+ids[j]+"'class='enemy' onclick=''></td>";
        }
         text += "</tr>";
    } 
    text += "</table> </div>";

    
    change.innerHTML = text;

}

function changeSound(){
	if (mute == false){
		$("#sound").removeClass("soundUnMuted");
		$("#sound").addClass("soundMuted");
		mute = true;
	}
	else{
		$("#sound").removeClass("soundMuted");
		$("#sound").addClass("soundUnMuted");
		mute = false;
	}
}


function drawHead(){
	var text = "<table>";
	text+="<tr><td class='number'> #</td><td class='namecontent'>Nimi</td><td class='content'>V</td><td class='content'>K</td><td class='content'>V%</td></tr>";
	text+="</table>";
	document.getElementById("rightpaneltablehead").innerHTML = text;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

this.drawHighscores = function() {
	
	drawHead();
	
	var sqlAwnser = populateWithScore();
	
	var sqlArray = sqlAwnser.split(";;");
	
	for (var i=0; i<sqlArray.length-1;i++){
		sqlArray[i]=sqlArray[i].split(";");
	}
	
	var text = "<table>";
	
	var highscoresInner = document.getElementById("highscores");

	for (var j = 0; j < sqlArray.length-1; j++) {
		var percentage = (sqlArray[j][1]/sqlArray[j][2]);
		percentage = roundNumber(percentage, 2);
		percentage = Math.round(percentage*100);
        text+="<tr><td class='number'>"+(j+1)+"</td><td class='namecontent'>"+sqlArray[j][0]+"<td class='content'>"+sqlArray[j][1]+"</td><td class='content'>"+(sqlArray[j][2]-sqlArray[j][1])+"</td><td class='content'>"+percentage+"%</td></tr>";
        }
	text+="</table>";
	highscoresInner.innerHTML = text;
	
	if (document.getElementById("history")){
		document.getElementById("history").innerHTML = "M&auml;ngude ajalugu";
	}
	document.getElementById("rightpanelheading").innerHTML = "Edetabel";

	
};
var selectedrow;
this.selectedHistoryRowNr = -1;
function chooseHistoryGame(obj) {
	if(selectedrow==obj){
		selectedRowNr = -1;
		$(selectedrow).removeClass("select");
		selectedrow=0;
	}
	
	else{
		selectedHistoryRowNr = $(obj).index();
		$(selectedrow).removeClass("select");
		selectedrow = obj;
		$(selectedrow).addClass("select");
	}

	
}


function drawHistory() {
	
	var text = "<table id='historytable'>";
	var highscoresInner = document.getElementById("highscores");

	if (localStorage.battleShipHistory){
		
		var games = jQuery.parseJSON(localStorage.battleShipHistory);
		for (i in games){
			text+="<tr onclick='chooseHistoryGame(this)'><td class='number'>"+(parseInt(i)+1)+"</td><td class='historycontent'>"+games[i].player+
			"<td class='content'>vs</td><td class='historycontent'>" +games[i].opponent+"</td></tr>";
		}
		
	}
		
	text+="</table>";
	highscoresInner.innerHTML = text;
	document.getElementById("history").innerHTML = "Edetabel";
	document.getElementById("rightpanelheading").innerHTML = "M&auml;ngude ajalugu";
	
	var text2 = "<table>";
	text2 +="<tr><td class='number'> #</td><td class='historycontent'>M&auml;ngija 1</td><td class='content'>vs</td><td class='historycontent'>M&auml;ngija 2</td></tr>";
	text2 +="</table>";
	document.getElementById("rightpaneltablehead").innerHTML = text2;
}

function swapRightpanelContent() {
	if (client==null){
		$().toastmessage('showNoticeToast', "Palun logi sisse");
		return;
	}
	if (document.getElementById("history").innerHTML == "Edetabel") {
		drawHighscores();
	}
	else {
		drawHistory();
		}
}
var guide = false; //make sure guide cannot be shown multiple times at once
/**
 * Displays user guide by using a jquery.toastmessage library.
 */
function displayGuide(){
	var str = unescape("Nupud:<br>\
	Uus m%E4ng laseb alustada m%E4ngu ja kontrollida sellega seonduvat.<br>\
	M%E4ngude ajalugu nupp laseb valida ajaloo ja edetabeli vaatamise vahel.<br> \
	Esita uuesti lubab uuesti l%E4bi vaadata viimast m%E4ngu<br>\
	M%E4ngimiseks peab olema m%E4ngija end sisse loginud Facebooki kontoga.<br>\
	M%E4ngujuhend: <br>\
	1. Vajuta \"Uus m%E4ng\" <br>\
	2. Lohista laevad m%E4nguv%E4ljale ja alusta lahingut <br>\
	3. Tulista vastase laevu, valides ruute tema (punasel) v%E4ljakul");
	
	if (document.getElementById("newgame").innerHTML == unescape("Uus m%E4ng") && guide == false){
		$().toastmessage('showGuideToast', str);
		guide = true;
	}
}
/**
 * Displays information notifications and errors when user tries to start game without all ships.
 */
function newGame(){
	
	if (client==null){
		$().toastmessage('showNoticeToast', "Palun logi sisse");
		return;
	}
	if (beforeBattleCheck()==1){
		return;
	};
	
	if (document.getElementById("newgame").innerHTML == "Tagasi"){
		return;
	}
	
	
	if (document.getElementById("newgame").innerHTML == "Liitu"){
		
		if(GAMES[selectedRowNr].playerOne != "?" && GAMES[selectedRowNr].playerTwo != "?"
			|| GAMES[selectedRowNr].playerOne == client || GAMES[selectedRowNr].playerTwo == client){
			$().toastmessage('showNoticeToast', "Siia ei saa liituda!");
			return;
		}
		joinGame(client);
		setTimeout("activateBattleSystem()", 500);
		
		return;
	}
	
	for (i in GAMES){
		if (GAMES[i].playerOne==client || GAMES[i].playerTwo==client){
			$().toastmessage('showNoticeToast',unescape( "Oled juba %FChe m%E4ngu loonud!"));
			return;
		}
	}
	addNewGame(client);
	findOpponent();

		
	
}
this.activateBattleSystem = function(){
	drawGameBoards();
	if (window.innerWidth > 790) {
		$().toastmessage('showNoticeToast', "Paiguta laevad");
	}
	init();
	document.getElementById("newgame").innerHTML = "Alusta lahingut";
	
};
this.gameIsActive = false;
this.beforeBattleCheck = function(){
	if (document.getElementById("newgame").innerHTML == "Alusta lahingut"){
		
		if(SHIPLIST.length != 10){
			var text ="";
			if (SHIPLIST.length == 9){
				text = " laev on veel paigutamata";
			} else {
				text = " laeva on veel paigutamata";
			}
			if (window.innerWidth > 790) {
				$().toastmessage('showNoticeToast', 10-SHIPLIST.length + text);
			}
		}
		else{
			gameIsActive = true;
			prepareGame();
			
			
		}
		return 1;
	}
	return 0;
};

//enemyBoard contains all squares for enemy gameboard
this.enemyBoard = new Array();
//stores ship hitlists about enemy gameboard to update hit ship to sunk
this.enemyShipsHit = new Array();
this.playerTurn = true; //used to store whose turn is it
/**
 * Disables draggables, adds onclick events on enemy gameboard, replaces ship images with gameboard background, creates ships for computer.
 */
this.startGame = function (){
	$('.ship').draggable("disable");
	$('.enemy').click(enemyClick);
	$('.ship').addClass("hidden");
	
	for (i in SHIPLIST){
		for (j in SHIPLIST[i].itself){
			$(SHIPLIST[i].itself[j]).addClass("shipVisible");
		}
		for (j in SHIPLIST[i].nodrop){
			$(SHIPLIST[i].nodrop[j]).removeClass("nodrop");
		}
	}
	
};
function prepareGame() {
	
	var $arr = $(".enemy");
    $arr.each(function(i) {
            enemyBoard.push($arr[i]); //add all squares to the enemyBoard list
    });
    for (var i = 0; i<12; i++){ //create empty hitlists for all ships
        enemyShipsHit.push([]);
}
	//Send SHIPLIST to the server
	
	sendShipList(SHIPLIST);
	
}

this.drawLoginWindow = function(){
	
	if(client==null){
		var text = "<h2>Logi sisse:</h2><div id='loginname'></div>";
		text += "<div id='loginsubmit'><button class='facebookbutton' onclick='fblogin()'></button></div>";
		document.getElementById("login").innerHTML = text;
	} else {

		displayLogin();
	}
};

function fblogin() {
	if (FBstate != null) {
		var FBstring = "https://www.facebook.com/dialog/oauth?client_id="+FBAppID+"&redirect_uri="+FBredirect+"&state="+FBstate;
		window.location = FBstring;
	}
	
}

this.displayLogin = function(){
	updateLobby();
	updateHighscore();
	
	
	var text = "<h2>Sisse loginud:</h2><div class='logincontent'>"+client+"</div><div onclick='logOut()' class='logout'>Logi v&auml;lja</div>";
	document.getElementById("login").innerHTML = text;

};

function logOut(){
	
	sendLogOutToServer();
	client = null;
	drawLoginWindow();
	window.location.replace("index.html");
}